package com.kb.design.service.impl;


import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kb.design.common.MeException;
import com.kb.design.constant.Constants;
import com.kb.design.dto.BaiUser;
import com.kb.design.dto.CustomUserDTO;
import com.kb.design.entity.CustomUser;
import com.kb.design.entity.DesignDept;
import com.kb.design.entity.DesignUserPost;
import com.kb.design.entity.DesignUserRole;
import com.kb.design.mapper.postgreSQL.*;
import com.kb.design.service.CustomUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * (CustomUser)表服务实现类
 *
 * @author makejava
 * @since 2023-08-22 10:57:17
 */
@Service
@DS("slave-1")
public class CustomUserServiceImpl extends ServiceImpl<CustomUserMapper, CustomUser> implements CustomUserService {


    @Resource
    private DesignUserPostMapper userPostMapper;
    @Resource
    private DesignUserRoleMapper designUserRoleMapper;
    @Resource
    private CustomUserMapper userMapper;
    @Resource
    private DesignDeptMapper designDeptMapper;
    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public CustomUser queryById(Long id) {
        return null;
    }

    @Override
    public List<CustomUser> selectAll() {
//        LambdaQueryWrapper<CustomUser> queryWrapper = Wrappers.lambdaQuery();
//        queryWrapper.eq(CustomUser::getDelFlag,Constants.DEL_FLAG_NO);
        List<CustomUser> customUserList = userMapper.selectAll();
        customUserList.forEach(user -> {
            user.setNameAndCode(String.join(",", user.getName(), user.getCode()));
            user.setNameAndDept(String.join(" ", user.getName(), user.getCode(), user.getDeptName()));
        });
        return customUserList;
    }

    /**
     * 分页查询
     *
     * @param customUser 筛选条件
     * @return 查询结果
     */
    @Override
    public Page<CustomUser> queryByPage(CustomUserDTO customUser) {
        Page<CustomUser> page = new Page<>(customUser.getPageNo(), customUser.getPageSize());
//        if (Objects.nonNull(customUser.getDeptId())){
//            LambdaQueryWrapper<CustomUser> queryWrapper = Wrappers.lambdaQuery();
//            queryWrapper.eq(CustomUser::getDeptId,customUser.getDeptId());
//            //查询部门下的人
//            List<CustomUser> userList = userMapper.selectList(queryWrapper);
//            if (CollectionUtil.isNotEmpty(userList)) {
//                List<String> codeList = userList.stream()
//                        .map(CustomUser::getCode)
//                        .collect(Collectors.toList());
//                customUser.setDeptIdList(codeList);
//            }
//        }
            Page<CustomUser> customUserPage = userMapper.queryPage(page, customUser);
            List<CustomUser> records = customUserPage.getRecords();
            if (CollectionUtils.isNotEmpty(records)){
                for (CustomUser record : records) {
                    //查询岗位信息
                    List<DesignUserPost> designUserPosts = userPostMapper.queryUserPost(record.getId());
                    if (CollectionUtils.isNotEmpty(designUserPosts)) {
                        String result = designUserPosts.stream()
                                .map(DesignUserPost::getPostId)
                                .map(String::valueOf)  // 确保 postId 被转换为字符串
                                .collect(Collectors.joining(","));
                        record.setPostStr(result);
                    }
                    List<DesignUserRole> roleList = designUserRoleMapper.queryUserRole(record.getId());
                    if (CollectionUtils.isNotEmpty(roleList)) {
                       String result = roleList.stream()
                                .map(DesignUserRole::getRoleId)
                                .map(String::valueOf)  // 确保 postId 被转换为字符串
                                .collect(Collectors.joining(","));
                        record.setRoleStr(result);
                    }

                    record.setName2(record.getName());
                    record.setName(record.getCode());
                }
            return customUserPage;
        }
        return new Page<CustomUser>();
    }

    @Override
    public List<CustomUser> queryUserByParams(Long deptId ,String role) {
        if (Objects.nonNull(role)){
            return userMapper.queryUserByRole(deptId,role);
        }
        LambdaQueryWrapper<CustomUser> queryWrapper = Wrappers.lambdaQuery();
        //根据角色查询
        queryWrapper.eq(Objects.nonNull(deptId),CustomUser::getDeptId,deptId)
                .eq(CustomUser::getDelFlag,Constants.DEL_FLAG_NO);
        return userMapper.selectList(queryWrapper);
    }

    /**
     * 新增数据
     *
     * @param customUser 实例对象
     * @return 实例对象
     */
    @Override
    @DSTransactional
    public CustomUser insert(CustomUser customUser) {
        try {
            //校验工号唯一
            CustomUser user = userMapper.queryUserByCode(customUser.getCode());
            if (Objects.nonNull(user)){
                throw new MeException("工号已存在");
            }
            String nickName =this.queryNickName(customUser.getCode());
            customUser.setName(nickName);
            DesignDept designDept = designDeptMapper.selectById(customUser.getDeptId());
            customUser.setDeptName(designDept.getDeptName());
            this.userMapper.insert(customUser);
            //用户权限数据
            String postStr = customUser.getPostStr();
            //不为空字符串
            if (Objects.nonNull(postStr) && !postStr.isEmpty()){
                String[] parts = postStr.split(",");
                for (String part : parts) {
                    DesignUserPost post = new DesignUserPost();
                    post.setPostId(Long.valueOf(part));
                    post.setUserId(customUser.getId());
                    userPostMapper.insert(post);
                }
            }
            //角色
            String roleStr = customUser.getRoleStr();
            if (Objects.nonNull(roleStr)){
                String[] roleList = roleStr.split(",");
                for (String part : roleList) {
                    DesignUserRole role = new DesignUserRole();
                    role.setRoleId(Long.valueOf(part));
                    role.setUserId(customUser.getId());
                    designUserRoleMapper.insert(role);
                }
            }
            return customUser;
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }

    @Override
    public CustomUser editor(CustomUser customUser) {
        DesignDept designDept = designDeptMapper.selectById(customUser.getDeptId());
        customUser.setDeptName(designDept.getDeptName());
        customUser.setName(customUser.getName2());
        userMapper.updateById(customUser);
        //用户权限数据
        String postStr = customUser.getPostStr();
        if (Objects.nonNull(postStr)){
//            先删除
            LambdaQueryWrapper<DesignUserPost> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(DesignUserPost::getUserId,customUser.getId());
            userPostMapper.delete(queryWrapper);
            String[] parts = postStr.split(",");
            for (String part : parts) {
                DesignUserPost post = new DesignUserPost();
                post.setUserId(customUser.getId());
                post.setPostId(Long.valueOf(part));
                userPostMapper.insert(post);
            }
        }
        //角色数据
        String roleStr = customUser.getRoleStr();
        if (Objects.nonNull(roleStr)){
//            先删除
            LambdaQueryWrapper<DesignUserRole> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(DesignUserRole::getUserId,customUser.getId());
            designUserRoleMapper.delete(queryWrapper);
            String[] parts = roleStr.split(",");
            for (String part : parts) {
                DesignUserRole role = new DesignUserRole();
                role.setUserId(customUser.getId());
                role.setRoleId(Long.valueOf(part));
                designUserRoleMapper.insert(role);
            }
        }
        return customUser;
    }

    /**
     * 修改数据
     *
     * @param customUser 实例对象
     * @return 实例对象
     */
    @Override
    public void update(CustomUser customUser) {
        customUser.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(customUser);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        CustomUser customUser = new CustomUser();
        customUser.setId(id);
        customUser.setDelFlag(Constants.DEL_FLAG_YES);
        return userMapper.updateById(customUser)> 0;
    }

    @Override
    public String queryNickName(String code) {
        String url = "http://192.168.10.33:8092/getBaidaUserInfo?user_name=" + code;
        HttpResponse response = HttpUtil.createGet(url)
                .setConnectionTimeout(60000)
                .execute();
        if (!Objects.equals(response.getStatus(), HttpStatus.HTTP_OK)) {
            throw new RuntimeException("请求异常：" + response.body());
        }
        JSONObject jsonObject = JSONObject.parseObject(response.body());
        if (Objects.isNull(jsonObject)) {
            throw new RuntimeException("未查询到对应人员");
        }
        String nickName = jsonObject.getString("nick_name");
        if (Objects.isNull(nickName)) {
            throw new RuntimeException("所选节点人员异常，请联系管理员！");
        }
        return nickName;
    }

    @Override
    public BaiUser queryBaiUser(String code) {
        String url = "http://192.168.10.33:8092/getBaidaUserInfo?user_name=" + code;
        HttpResponse response = HttpUtil.createGet(url)
                .setConnectionTimeout(60000)
                .execute();
        if (!Objects.equals(response.getStatus(), HttpStatus.HTTP_OK)) {
            throw new RuntimeException("请求异常：" + response.body());
        }
        JSONObject jsonObject = JSONObject.parseObject(response.body());
        if (Objects.isNull(jsonObject)) {
            throw new RuntimeException("未查询到对应人员: " + code);
        }
        BaiUser baiUser = jsonObject.toJavaObject(BaiUser.class);
        if (Objects.isNull(baiUser)) {
            throw new RuntimeException("所选节点人员异常，请联系管理员！");
        }
        return baiUser;
    }

    @Override
    public List<CustomUser> queryUserByDeptFunctions(String deptFunctions) {
        return userMapper.queryUserByDeptFunctions(deptFunctions);
    }
}
